package com.hsogoo.collate.quartz;

import com.hsogoo.collate.domain.CollateConfig;
import com.hsogoo.collate.service.CollateConfigManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 对账配置扫描器
 * 用来监控是否有新的对账配置加入
 * 并且把任务加入到调度器
 * @Author huangsaigang
 * Created @2019-10-28.
 */
@Slf4j
@Service
public class CollateConfigScanner extends QuartzJobBean {

    @Autowired
    private CollateConfigManager collateConfigManager;
    @Autowired
    private SchedulerManager schedulerManager;
    @Autowired
    private SchedulerJobCreator schedulerJobCreator;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String jobName = jobExecutionContext.getJobDetail().getKey().getName();
        log.info("[{}] is running...", jobName);
        List<CollateConfig> collateConfigs = collateConfigManager.getCollateConfigs();
        //不存在的添加新任务
        if(CollectionUtils.isNotEmpty(collateConfigs)){
            for(CollateConfig collateConfig : collateConfigs){
                if(!JobDetailRepository.containJob(collateConfig.getTaskName())){
                    SchedulerJob job = schedulerJobCreator.create(collateConfig);
                    log.info("scan job add a new job [{}], cron[{}]", job.getJobName(), job.getCronExpression());
                    schedulerManager.addJob(job);
                }
            }
        }
    }
}
